package cn.tedu.egmybatis6.conmon.exception;

import cn.tedu.egmybatis6.conmon.response.JsonResult;
import cn.tedu.egmybatis6.conmon.response.StataCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandle {
    @ExceptionHandler
    public JsonResult handleConstraintViolationException(ConstraintViolationException e){
        String data = e.getMessage().split(":")[1].trim();
        log.error("ConstraintViolationException:"+ data);
        return new JsonResult(StataCode.VALIDATED_ERROR,data);
    }

    @ExceptionHandler
    public JsonResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        String data = e.getFieldError().getDefaultMessage();
        log.error("MethodArgumentNotValidException:"+ data);
        return new JsonResult(StataCode.VALIDATED_ERROR,data);
    }
    @ExceptionHandler
    public JsonResult handleThrowable(Throwable e){
        String data = e.getMessage();
        log.error("Throwable:"+ data);
        return new JsonResult(StataCode.THROWABLE_ERROR,data);
    }
}
